<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>生命周期勾子</title>
  <script src="js/vue.min.js"></script>
</head>

<body>
  <div id="app">    
  </div>
  <script>
    let app = Vue.createApp({
      template: `<div>
      <test-comp />
      {{count}} 
      <button @click="handleCountUpdate">更新count</button>
      <div>
        生命周期的执行顺序：父beforeCreate->父created->父beforeMount -> 子beforeCreate->子created->子beforeMount->子mounted ->父mounted
      </div>
      <div>
        生命周期勾子函数beforeUpdate是数据更新后触发，此时页面的dom还未发生变化，而updated勾子之后，dom就更新了<br />
        父beforeUpdate->子beforeUpdate->子updated->父updated
      </div>
      </div>`,
      data() {
        return { count: 1 }
      },
      methods: {
        handleCountUpdate() {
          this.count += 1
        }
      },
      beforeCreate() {
        // 在这个勾子之前 初始化 events和lifecycle
        console.log('beforeCreate', '实例被创建之前, this.count为undefined', this.count) // 此时的count为undefined
      },
      created() {
        // 在这个勾子之前 初始化 injections 和 reactivity
        console.log('created', '实例被创建之后', this.count)
      },
      beforeMount() {
        // 在这个勾子之前 将 template编译成 render function
        console.log('beforeMount', '实例被挂载之前,this.$el为null', this.$el)
      },
      mounted() {
        console.log('mounted', '实例被挂载之后,此时可以访问到this.$el', this.$el)
      },
      beforeUpdate() {
        // 数据更新后，此时视图是还未更新的
        console.log('beforeUpdate', '数据更新之前', this.$el.innerHTML)
      },
      updated() {
        console.log('updated', '数据更新之后', this.$el.innerHTML)
      },
      beforeUnmount() {
        // app.unmount() 调用后，实例将被销毁
        console.log('beforeUnmount', '实例被销毁之前', this.$el.innerHTML)
      },
      unmounted() {
        console.log('unmounted', '实例销毁后', this.count)
        app = null
      }
    })

    app.component('test-comp', {
      template: `<div>我是子组件</div>`,
      beforeCreate() {
        console.log('子组件的beforeCreate')
      },
      created() {
        console.log('子组件的created')
      },
      beforeMount() {
        console.log('子组件的beforeMount')
      },
      mounted() {
        console.log('子组件的mounted')
      },
    })

    const vm = app.mount('#app')

    // vm.unmount()
  </script>
</body>

</html>